package com.runa.monitor.platinterface.netservice.handler;

import com.runa.monitor.platinterface.base.AnalysisFactory;
import com.runa.monitor.platinterface.netservice.equipment.dtu.DtuResponseHandler;
import com.runa.monitor.platinterface.netservice.equipment.dtu.furuisi.FuRuiSiClientHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author zhuj
 */
public class ConcenChannelInitializer extends ChannelInitializer {

    private RccReportHandler reportHandler = new RccReportHandler();

    private RccResponseHandler responseHandler;

    private DtuResponseHandler dtuResponseHandler;

    private String protocol;

    private boolean isTcp;

    public ConcenChannelInitializer(String protocol, boolean isTcp) {
        this.isTcp = isTcp;
        this.protocol = protocol;
        responseHandler = new RccResponseHandler();
        dtuResponseHandler = new DtuResponseHandler();
    }

    @Override
    protected void initChannel(Channel ch) {
        ch.pipeline().addLast(new IdleStateHandler(120, 240, 360));
        if (isTcp) {
            ch.pipeline().addLast(new ProtocolDecoder(AnalysisFactory.create(protocol)));
            ch.pipeline().addLast(new ProtocolEncoder());
        } else {
            ch.pipeline().addLast(new DatagramDecoder(AnalysisFactory.create(protocol)));
            ch.pipeline().addLast(new DatagramEncoder());
            ch.pipeline().addLast(new UdpReportHandler());
        }
        ch.pipeline().addLast(reportHandler);
        ch.pipeline().addLast(responseHandler);
        ch.pipeline().addLast(dtuResponseHandler);
        ch.pipeline().addLast(new FuRuiSiClientHandler());
        //此处不可用idle来处理超时，idle的原理是监测通道内的读、写操作，
        //在指定时间内没发生读写操作即触发回调，不符合集中器的实际机制。
        //ch.pipeline().addLast(newComm IdleStateHandler(60, 60, 60));
    }
}
